//
//  AIChatBoardView.m
//  Mia
//
//  Created by Vill on 2024/1/18.
//

#import "AIChatBoardView.h"
#import "AIChatTextView.h"
#import "UITextView+Placeholder.h"

@interface AIChatBoardView ()<UITextViewDelegate>

@property (nonatomic, strong) UIView *containView;  // 容器
@property (nonatomic, assign) float keyboardHeight; //键盘高度

@property (nonatomic, strong) UIButton *pictureBtn;
@property (nonatomic, strong) AIChatTextView *textView; // 文本view
@property (nonatomic, strong) UIButton *askBtn;   //问题按钮

@property (nonatomic, strong) UIButton *videoBtn;  //视频
@property (nonatomic, strong) UIButton *voiceBtn;  //语音

@property (nonatomic, assign) NSInteger textViewHeight; //文本高度

@end

@implementation AIChatBoardView


-(instancetype)initWithFrame:(CGRect)frame{
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.clearColor;
        //监听键盘出现、消失
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
        //此通知主要是为了获取点击空白处回收键盘的处理
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide) name:@"keyboardHide" object:nil];
        //创建视图
        [self creatSubView];
    }
    return self;
}

-(void)creatSubView{
    self.textViewHeight = PTW(30);
    
    [self addSubview:self.pictureBtn];
    [self.pictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(40));
        make.leading.mas_equalTo(self).mas_offset(PTW(12.5));
        make.bottom.mas_equalTo(self).mas_offset(-PTW(7.5));
    }];
    [self addSubview:self.containView];
    [self.containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.pictureBtn.mas_trailing).mas_offset(PTW(10));
        make.trailing.mas_equalTo(self).mas_offset(-PTW(12.5));
        make.top.mas_equalTo(self).mas_offset(PTW(5));
        make.bottom.mas_equalTo(self).mas_offset(-PTW(5));
    }];
    
    [self.containView addSubview:self.askBtn];
    [self.askBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(30));
        make.leading.mas_equalTo(self.containView).mas_offset(PTW(10));
        make.bottom.mas_equalTo(self.containView).mas_offset(-PTW(7));
    }];
    
    [self.containView addSubview:self.videoBtn];
    [self.containView addSubview:self.voiceBtn];
    [self.videoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(30));
        make.trailing.mas_equalTo(self.containView).mas_offset(-PTW(10));
        make.centerY.mas_equalTo(self.askBtn);
    }];
    [self.voiceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(30));
        make.trailing.mas_equalTo(self.videoBtn.mas_leading).mas_offset(-PTW(5));
        make.centerY.mas_equalTo(self.askBtn);
    }];
    [self.containView addSubview:self.textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.askBtn.mas_trailing).mas_offset(PTW(3));
        make.trailing.mas_equalTo(self.containView).mas_offset(-PTW(80));
        make.centerY.mas_equalTo(self.containView);
        make.height.mas_equalTo(PTW(30));
    }];
}

#pragma mark ----------------- func --------------
// 点击图片按钮
- (void)picAction:(UIButton *)btn{
    [self.textView resignFirstResponder];
    [self selectButtonType:0];
}

// 视频按钮点击
- (void)videoAction{
    [self.textView resignFirstResponder];
    [self selectButtonType:3];
}

// 语音按钮点击
-(void)voiceAction{
    [self.textView resignFirstResponder];
    [self selectButtonType:2];
}

// 问题点击
-(void)askAction{
    [self.textView resignFirstResponder];
    [self selectButtonType:1];
}

-(void)selectButtonType:(NSInteger)index{
    //改变更多、self的frame
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, KScreenHeight - self.containView.height - PTW(10) - KBottomSafeHeight, KScreenWidth, self.containView.height + PTW(10));
        [self changeTableViewFrame];
    }];
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectButtonWithType:)]) {
        [self.delegate selectButtonWithType:index];
    }
}

#pragma mark ====== 改变输入框大小 ======
- (void)changeFrame:(CGFloat)height {
    CGRect frame = self.textView.frame;
    frame.size.height = height;
    self.textViewHeight = height;
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    self.frame = CGRectMake(0, KScreenHeight - height - self.keyboardHeight - PTW(30), KScreenWidth, height + PTW(30));
    //主要是为了改变VC的tableView的frame
    [self changeTableViewFrame];
}

#pragma mark ====== 改变tableView的frame ======
- (void)changeTableViewFrame {
    if (self.delegate && [self.delegate respondsToSelector:@selector(keyboardChangeFrameWithMinY:)]) {
        [self.delegate keyboardChangeFrameWithMinY:self.y];
    }
}

#pragma mark ====== 点击空白处，键盘收起时，移动self至底部 ======
- (void)keyboardHide {
    //收起键盘
    [self.textView resignFirstResponder];
    [UIView animateWithDuration:0.25 animations:^{
        //设置self的frame到最底部
        NSLog(@"%.2f",self.containView.height);
        self.frame = CGRectMake(0, KScreenHeight - self.containView.height - PTW(10) - KBottomSafeHeight, KScreenWidth, self.containView.height + PTW(10));
        [self changeTableViewFrame];
    }];
}

#pragma mark ====== 键盘将要出现 ======
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //获取键盘的高度
    self.keyboardHeight = endFrame.size.height;
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.textViewHeight);
    }];
    //键盘的动画时长
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration delay:0 options:[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue] animations:^{
//        self.frame = CGRectMake(0, endFrame.origin.y - self.height , KScreenWidth, self.height);
        if (self.textViewHeight < PTW(30)){
            self.frame = CGRectMake(0, KScreenHeight - PTW(30) - self.keyboardHeight - PTW(25), KScreenWidth, PTW(30) + PTW(25));
        }else{
            self.frame = CGRectMake(0, KScreenHeight - self.textViewHeight - self.keyboardHeight - PTW(25), KScreenWidth, self.textViewHeight + PTW(25));
        }
        [self changeTableViewFrame];
    } completion:nil];
}

#pragma mark ====== 键盘将要消失 ======
- (void)keyboardWillHide:(NSNotification *)notification {
    [UIView animateWithDuration:0.25 animations:^{
        if (self.textViewHeight < PTW(30)){
            self.frame = CGRectMake(0, KScreenHeight - PTW(30) - PTW(22) - KBottomSafeHeight, KScreenWidth, PTW(30) + PTW(22));
        }else{
            self.frame = CGRectMake(0, KScreenHeight - self.textViewHeight - PTW(20) - KBottomSafeHeight, KScreenWidth, self.textViewHeight + PTW(20));
        }
        [self changeTableViewFrame];
    }];
}

// 开始展示
- (void)changeFrameWithNumberOfRows{
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(PTW(30));
    }];
    self.frame = CGRectMake(0, KScreenHeight - PTW(52) - KBottomSafeHeight, KScreenWidth, PTW(52));
    [self changeTableViewFrame];
}

// 执行在UITextView成为第一响应者时要执行的操作
- (void)textViewDidBeginEditing:(UITextView *)textView{
//    NSLog(@"------- 我是第一响应者 -------- ");
    if (self.delegate && [self.delegate respondsToSelector:@selector(keyboardWillBeginStartEdit:)]) {
        [self.delegate keyboardWillBeginStartEdit:YES];
    }
}

// 执行在UITextView不是第一响应者时要执行的操作
- (void)textViewDidEndEditing:(UITextView *)textView{
//    NSLog(@"------- 我不是第一响应者 -------- ");
    if (self.delegate && [self.delegate respondsToSelector:@selector(keyboardWillBeginStartEdit:)]) {
        [self.delegate keyboardWillBeginStartEdit:NO];
    }
}

#pragma mark ====== 点击发送按钮 ======
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    // 获取当前文本长度
    NSUInteger newLength = textView.text.length + text.length - range.length;
    //判断输入的字是否是回车，即按下return
    if ([text isEqualToString:@"\n"]){
        [self animateView:NO];
        if (self.delegate && [self.delegate respondsToSelector:@selector(textViewContentText:)]) {
            [self.delegate textViewContentText:textView.text];
        }
        [self changeFrame:PTW(22)];
        textView.text = @"";
        /*这里返回NO，就代表return键值失效，即页面上按下return，
         不会出现换行，如果为yes，则输入页面会换行*/
        return NO;
    }
    // 检查是否超过指定的长度
    if (newLength <= 500) { // 这里假设最大长度为 500
        if(newLength == 500){
//            NSLog(@"文本长度超过限制500");
            [SVProgressHUD showInfoWithStatus:@"The input is too long, within 500 characters!"];
            [SVProgressHUD dismissWithDelay:1];
        }
        return YES;
    } else {
        return NO;
    }
    return YES;
}


- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length > 0){
        [self animateView:YES];
    }else{
        [self animateView:NO];
    }
}

- (void)animateView:(BOOL)isBeginEdit {
    if (isBeginEdit){
        [UIView animateWithDuration:1.0 animations:^{
            self.videoBtn.transform = CGAffineTransformMakeScale(0.01, 0.01);
            self.videoBtn.alpha = 0;
            self.voiceBtn.transform = CGAffineTransformMakeScale(0.01, 0.01);
            self.voiceBtn.alpha = 0;
        } completion:^(BOOL finished) {
        }];
        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(self.containView).mas_offset(-PTW(15));
        }];
        
    }else{
        [UIView animateWithDuration:1.0 animations:^{
            self.videoBtn.transform = CGAffineTransformMakeScale(1.0, 1.0);
            self.videoBtn.alpha = 1;
            self.voiceBtn.transform = CGAffineTransformMakeScale(1.0, 1.0);
            self.voiceBtn.alpha = 1;
        } completion:^(BOOL finished) {
        }];
        [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(self.containView).mas_offset(-PTW(80));
        }];
    }
}

#pragma mark ----------------- lazy --------------
- (UIView *)containView {
    if (!_containView) {
        _containView = [UIView new];
        _containView.backgroundColor = [UIColor colorHex:@"#333333" alpha:0.4];
        _containView.layer.cornerRadius = PTW(15);
        _containView.layer.masksToBounds = YES;
    }
    return _containView;
}

- (UIButton *)pictureBtn{
    if(!_pictureBtn){
        _pictureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_pictureBtn setImage:KImaged(@"ai_home_pic") forState:UIControlStateNormal];
        [_pictureBtn addTarget:self action:@selector(picAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pictureBtn;
}

- (UIButton *)askBtn{
    if(!_askBtn){
        _askBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_askBtn setImage:KImaged(@"ai_home_msg") forState:UIControlStateNormal];
        [_askBtn addTarget:self action:@selector(askAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _askBtn;
}

- (AIChatTextView *)textView {
    if (!_textView) {
        _textView = [[AIChatTextView alloc] init];
        _textView.font = [UIFont fontWithWeight:Medium size:PTW(15)];
        [_textView textValueDidChanged:^(CGFloat textHeight) {
            [self changeFrame:textHeight];
        }];
        _textView.maxNumberOfLines = 3;
        _textView.delegate = self;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.textContainerInset = UIEdgeInsetsMake(PTW(2), 0, 0, 0); // 内边距
        _textView.placeholder = @"Type something";
        _textView.placeholderColor = [UIColor colorHex:@"#FFFFFF" alpha:0.5];
        _textView.backgroundColor = [UIColor clearColor];
        _textView.textColor = UIColor.whiteColor;
//        _textView.contentInset = UIEdgeInsetsMake(PTW(2), 0, PTW(2), 0);
        _textView.layoutManager.allowsNonContiguousLayout = NO;
    }
    return _textView;
}

- (UIButton *)voiceBtn{
    if(!_voiceBtn){
        _voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_voiceBtn setImage:KImaged(@"ai_home_voice") forState:UIControlStateNormal];
        [_voiceBtn addTarget:self action:@selector(voiceAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _voiceBtn;
}

- (UIButton *)videoBtn{
    if(!_videoBtn){
        _videoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_videoBtn setImage:KImaged(@"ai_home_video") forState:UIControlStateNormal];
        [_videoBtn addTarget:self action:@selector(videoAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _videoBtn;
}

#pragma mark ====== 移除监听 ======
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
